import asyncio

from loguru import logger

from com.arcfox.util import async_request as requests, util
import time

base_url = "http://webapi.http.zhimacangku.com/getip?type=2&pro=&city=0&yys=0&port=1&pack=235693&ts=0&ys=0&cs=0&lb=1&sb=0&pb=45&mr=1&regions="


# base_url_test = "http://webapi.http.zhimacangku.com/getip?type=2&pro=&city=0&yys=0&port=1&pack=29238&ts=0&ys=0&cs=0&lb=1&sb=0&pb=45&mr=1&regions="


async def get_proxy(size=1):
    full_url = f"{base_url}&num={size}"
    try:
        resp = await requests.get_with_session(full_url, timeout=3)
        logger.info(resp.json())
        if resp.code == 200:
            result_json = resp.json()
            data_list = result_json['data']
            if data_list:
                return {
                    "ip": data_list[0]['ip'],
                    "port": data_list[0]['port'],
                }
    except Exception as e:
        logger.exception("芝麻代理获取异常", e)
    return None


async def get_proxy_list(size=1):
    full_url = f"{base_url}&num={size}"
    try:
        resp = await requests.get_with_session(full_url, timeout=3)
        logger.info(resp.json())
        if resp.code == 200:
            result_json = resp.json()
            data_list = result_json['data']
            if data_list:
                proxy_list = []
                for data in data_list:
                    proxy_list.append({
                        "ip": data['ip'],
                        "port": data['port'],
                    })
                return proxy_list
    except Exception as e:
        logger.exception("芝麻代理获取异常", e)
    return None


def format_proxy(proxy, is_https=False):
    if proxy:
        if is_https:
            return f"https://{proxy['ip']}:{str(proxy['port'])}"
        else:
            return f"http://{proxy['ip']}:{str(proxy['port'])}"
    return None


async def test():
    proxy = await get_proxy()
    print(proxy)
    # formatted_proxy = format_proxy(proxy[0])
    # try:
    #     for i in range(1, 4):
    #         resp = await requests.get_with_session("http://httpbin.org/get", proxy="http://125.23.25.63:8888",
    #                                                timeout=3)
    #     # print(resp.json())
    # except Exception as e:
    #     logger.info("请求超时2222")


def get_base_params():
    user = "test2"
    password = "e4e8506f06"
    t = str(int(time.time()))
    src = user + t + password
    sign = util.get_md5(src)
    params = {"license": user, "time": t, "sign": sign}
    return params


async def get_abyun_proxy():
    url = "https://api-ip.abuyun.com/obtain"
    params = get_base_params()
    params['limit'] = 1
    response = await requests.get_with_session(url, params=params, timeout=3)
    result_json = response.json()
    return f"http://{result_json['proxies'][0]}"


if __name__ == "__main__":
    asyncio.run(get_abyun_proxy())
